<!--
 * @Author: 徐凯 xukai@sinoroad.com
 * @Date: 2023-11-30 17:49:31
 * @Description: echarts
-->
<template>
  <div
    :id="id"
    :class="className"
    class="m-echarts"
    :style="{ height: height, width: width }"
    ref="myEcharts"
  />
</template>

<script setup>
import { onMounted, ref, nextTick, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import tdTheme from './theme.json' // 引入默认主题
import { echartsHighlightAnimation } from './util'
import chartResize from '@/common/hooks/chartResize.js'
chartResize()

const { options, highLight } = defineProps({
  id: String, // id
  className: String, // 类名
  width: String, // 宽度
  height: String, // 高度
  options: Object, // 配置项
  highLight: Number // x轴数据长度
})

const chart = ref(null) // echarts实例
const timer = ref(null) // 定时器
const myEcharts = ref(null) // echarts DOM元素

watch(
  options,
  () => {
    nextTick(() => {
      // 设置true清空echart缓存
      chart.value.setOption(getOptions(), true)
    })
  },
  { deep: true }
)

onMounted(() => {
  echarts.registerTheme('tdTheme', tdTheme) // 覆盖默认主题
  nextTick(() => {
    initChart()
  })
})

/**
 * 卸载前的钩子
 */
onBeforeUnmount(() => {
  chart.value.dispose()
  chart.value = null
  clearInterval(timer.value)
})

/**
 * 初始化Echarts
 */
const initChart = () => {
  // 初始化echart
  chart.value = echarts.init(myEcharts.value, 'tdTheme')
  chart.value.setOption(getOptions(), true)
  // 初始化高亮动画
  highLight && (timer.value = echartsHighlightAnimation(chart.value, highLight))
}

/**
 * 获取配置项
 */
const getOptions = () => {
  const defaultOptions = {
    tooltip: {},
    grid: {
      bottom: 20
    },
    legend: {
      textStyle: { color: '#FFFFFF' }
    }
  }
  return Object.assign({}, defaultOptions, options)
}
</script>

<script>
export default { name: 'MyEcharts' }
</script>

<style lang="scss" scoped></style>
